﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using Microsoft.Office.Word.Server.Conversions;

namespace WordConversionManager.WordConversionReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class WordConversionReceiver : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            CreateConversionJob(properties);

            base.ItemAdded(properties);
        }

        public override void ItemCheckedIn(SPItemEventProperties properties)
        {
            CreateConversionJob(properties);

            base.ItemCheckedIn(properties);
        }

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            CreateConversionJob(properties);

            base.ItemUpdated(properties);
        }

        public static string Combine(string uri1, string uri2)
        {
            uri1 = uri1.TrimEnd('/');
            uri2 = uri2.TrimStart('/');
            return string.Format("{0}/{1}", uri1, uri2);
        }

        private string GetExtension(string FileName)
        {
            return FileName.Substring(FileName.LastIndexOf(".") + 1, FileName.Length - FileName.LastIndexOf(".") - 1);
        }

        private string GetFileName(string FileName)
        {
            return FileName.Substring(0, FileName.LastIndexOf("."));
        }

        private string GetFile(string FileName, string FileExtension)
        {
            return string.Format("{0}.{1}", FileName, FileExtension);
        }

        private void CreateConversionJob(SPItemEventProperties properties)
        {
            string fileExtension = GetExtension(properties.ListItem.File.Name);

            if (WordConversionManagerSetttings.GetSupportedFileFormats(properties.List).Contains(fileExtension.ToLower()))
            {
                SaveFormat outputFileFormat;
                string wordServiceApplicationProxy = WordConversionManagerSetttings.GetWordServiceApplicationProxy(properties.Web);
                ConversionJob job;

                Guid destionationListGuid;
                if (Utilities.IsGuid(WordConversionManagerSetttings.GetDestinationList(properties.List), out destionationListGuid))
                {
                    SPList destionationList = properties.Web.Lists[destionationListGuid];
                    OverwriteMethod overwriteMethod = WordConversionManagerSetttings.GetOverwriteSetting(properties.List);
                    string newFileName;

                    foreach (string outputFileFormatString in WordConversionManagerSetttings.GetOutputFileFormats(properties.List))
                    {
                        outputFileFormat = (SaveFormat)Enum.Parse(typeof(SaveFormat), outputFileFormatString);
                        newFileName = GetFile(GetFileName(properties.ListItem.File.Name), outputFileFormatString);

                        bool createNewFile = true;

                        if (overwriteMethod == OverwriteMethod.SaveAppendUnique)
                        { 
                            if(destionationList.RootFolder.Files[Combine(destionationList.RootFolder.Url, newFileName)]!=null)
                            {
                                newFileName = GetFile(GetFileName(properties.ListItem.File.Name) + "_" + Guid.NewGuid().ToString(), outputFileFormatString);
                            }
                        }
                        else if (overwriteMethod == OverwriteMethod.Discharge && destionationList.RootFolder.Files[Combine(destionationList.RootFolder.Url, newFileName)] != null)
                        {
                            createNewFile = false;
                        }

                        if (createNewFile)
                        {
                            job = new ConversionJob(wordServiceApplicationProxy);
                            job.UserToken = properties.Web.CurrentUser.UserToken;
                            job.Settings.UpdateFields = true;
                            job.Settings.OutputFormat = outputFileFormat;
                            job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
                            job.AddFile(Combine(properties.WebUrl, properties.ListItem.Url),
                                         Combine(properties.WebUrl + "/" + destionationList.RootFolder.Url, newFileName));
                            job.Start();
                        }
                    }
                    
                }
            }
        }


    }
}
